<template>
  <view class="coupon-detail-page">
    <!-- 导航栏 -->
    <NavBar title="优惠券详情" />

    <!-- 优惠券信息 -->
    <view class="coupon-card" :class="{ 'used': coupon.status === 'used', 'expired': coupon.status === 'expired' }">
      <view class="coupon-header">
        <view class="coupon-amount">
          <text class="symbol">¥</text>
          <text class="value">{{ coupon.amount }}</text>
        </view>
        <view class="coupon-condition">满{{ coupon.minAmount }}元可用</view>
      </view>
      
      <view class="coupon-info">
        <view class="info-item">
          <view class="info-label">优惠券名称</view>
          <view class="info-value">{{ coupon.name }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">使用范围</view>
          <view class="info-value">{{ coupon.scope }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">有效期</view>
          <view class="info-value">{{ coupon.validTimeDesc }}</view>
        </view>
        <view class="info-item" v-if="coupon.code">
          <view class="info-label">优惠券码</view>
          <view class="info-value code">{{ coupon.code }}</view>
        </view>
      </view>

      <view class="coupon-status" v-if="coupon.status !== 'unused'">
        <image 
          :src="coupon.status === 'used' ? usedStamp : expiredStamp" 
          class="status-stamp"
        />
      </view>
    </view>

    <!-- 使用说明 -->
    <view class="detail-section">
      <view class="section-title">使用说明</view>
      <view class="section-content">
        <view class="instruction-item">1. 本优惠券仅限在有效期内使用</view>
        <view class="instruction-item">2. 优惠券不可与其他优惠券叠加使用</view>
        <view class="instruction-item">3. 每个订单限用一张优惠券</view>
        <view class="instruction-item">4. 优惠券不可兑换现金，不设找零</view>
        <view class="instruction-item" v-if="coupon.description">{{ coupon.description }}</view>
      </view>
    </view>

    <!-- 使用规则 -->
    <view class="detail-section">
      <view class="section-title">使用规则</view>
      <view class="section-content">
        <view class="rule-item">1. {{ coupon.scope }}商品可用</view>
        <view class="rule-item">2. 订单金额满{{ coupon.minAmount }}元可用</view>
        <view class="rule-item">3. 优惠券有效期至{{ coupon.validTimeDesc.split('~')[1].trim() }}</view>
        <view class="rule-item">4. 使用后不可退回</view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="detail-footer" v-if="coupon.status === 'unused'">
      <view class="footer-buttons" v-if="!fromOrder">
        <nut-button type="primary" @click="useCoupon">立即使用</nut-button>
        <nut-button type="info" @click="shareCoupon">分享优惠券</nut-button>
      </view>
      <nut-button v-else type="primary" block @click="useCoupon">选择此优惠券</nut-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import NavBar from '@/components/NavBar/index.vue'
import userApi from '@/api/user'
import type { CouponItem } from '@/api/types'
import { useLoading } from '@/hooks/useLoading'

// 获取路由参数
const router = Taro.getCurrentInstance().router
const couponId = router?.params?.id
const fromOrder = router?.params?.from === 'order'
const selectedCategoryId = router?.params?.categoryId
const minAmount = router?.params?.amount

// 优惠券信息
const coupon = ref<CouponItem>({
  id: '',
  name: '',
  amount: 0,
  minAmount: 0,
  scope: '',
  validTimeDesc: '',
  status: 'unused'
})

// 加载状态
const { loading, setLoading } = useLoading()

// 状态图片
const usedStamp = 'https://img01.yzcdn.cn/vant/coupon-used.png'
const expiredStamp = 'https://img01.yzcdn.cn/vant/coupon-expired.png'

// 获取优惠券详情
const getCouponDetail = async () => {
  if (!couponId) {
    Taro.showToast({
      title: '优惠券ID不存在',
      icon: 'none'
    })
    setTimeout(() => {
      Taro.navigateBack()
    }, 1500)
    return
  }

  try {
    showLoading('加载中...')
    
    // 尝试从API获取优惠券详情
    try {
      // 从优惠券列表API中获取指定ID的优惠券
      const res = await userApi.getCouponList()
      const foundCoupon = res.data.find((item: CouponItem) => item.id.toString() === couponId.toString())
      
      if (foundCoupon) {
        coupon.value = foundCoupon
      } else {
        throw new Error('未找到优惠券')
      }
    } catch (apiError) {
      console.error('API获取优惠券详情失败，使用模拟数据', apiError)
      
      // 如果API调用失败，使用模拟数据
      coupon.value = {
        id: couponId,
        name: '满减优惠券',
        code: 'MALL2023',
        amount: '50',
        minAmount: '300',
        scope: '全场通用',
        categoryId: '',
        validTimeDesc: '2023-06-01 ~ 2023-07-01',
        status: 'unused',
        description: '本优惠券为满减券，购物满300元可使用'
      }
      
      // 显示提示，但不中断流程
      Taro.showToast({
        title: '使用本地数据显示',
        icon: 'none',
        duration: 1500
      })
    }
  } catch (error) {
    console.error('获取优惠券详情失败', error)
    Taro.showToast({
      title: '获取优惠券详情失败',
      icon: 'none'
    })
    setTimeout(() => {
      Taro.navigateBack()
    }, 1500)
  } finally {
    hideLoading()
  }
}

// 使用优惠券
const useCoupon = () => {
  if (coupon.value.status !== 'unused') {
    Taro.showToast({
      title: coupon.value.status === 'used' ? '该优惠券已使用' : '该优惠券已过期',
      icon: 'none'
    })
    return
  }
  
  // 检查优惠券是否可用（从订单页面进入时需要检查金额条件）
  if (fromOrder && minAmount) {
    if (Number(coupon.value.minAmount) > Number(minAmount)) {
      Taro.showToast({
        title: `订单金额不满${coupon.value.minAmount}元`,
        icon: 'none'
      })
      return
    }
    
    // 如果是从订单页面跳转来的，选择优惠券后返回
    const pages = Taro.getCurrentPages()
    const prevPage = pages[pages.length - 2]
    
    // 向上一页传递选中的优惠券
    if (prevPage) {
      // 实际项目中应该使用更好的状态管理方式
      prevPage.$instance.ctx.selectedCoupon = coupon.value
      
      Taro.showToast({
        title: '已选择优惠券',
        icon: 'success'
      })
    }
    
    Taro.navigateBack()
  } else {
    // 根据优惠券类型跳转到相应页面
    if (coupon.value.categoryId) {
      // 如果有分类ID，跳转到对应分类
      Taro.navigateTo({
        url: `/pages/category/category-detail?id=${coupon.value.categoryId}&name=${coupon.value.scope}`
      })
    } else {
      // 全场通用券跳转到首页
      Taro.switchTab({
        url: '/pages/index/index'
      })
    }
  }
}

// 分享优惠券
const shareCoupon = () => {
  // 在小程序环境中使用小程序的分享API
  if (Taro.getEnv() === Taro.ENV_TYPE.WEAPP) {
    Taro.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    
    // 触发分享面板
    Taro.showShareMenu()
    
    // 设置分享内容
    Taro.onShareAppMessage(() => {
      return {
        title: `${coupon.value.name} - 满${coupon.value.minAmount}减${coupon.value.amount}`,
        path: `/pages/coupon/detail?id=${coupon.value.id}`,
        imageUrl: 'https://img01.yzcdn.cn/vant/coupon-background.png' // 分享图片
      }
    })
  } else {
    // 在H5环境下模拟分享行为
    Taro.showActionSheet({
      itemList: ['分享到微信', '分享到朋友圈', '复制链接'],
      success: function(res) {
        if (res.tapIndex === 2) {
          // 复制链接
          const shareLink = `${window.location.origin}/pages/coupon/detail?id=${coupon.value.id}`
          Taro.setClipboardData({
            data: shareLink,
            success: function() {
              Taro.showToast({
                title: '链接已复制',
                icon: 'success'
              })
            }
          })
        } else {
          // 其他分享选项
          Taro.showToast({
            title: '分享功能开发中',
            icon: 'none'
          })
        }
      }
    })
  }
}

// 组件挂载时初始化
onMounted(() => {
  getCouponDetail()
})
</script>

<style lang="scss" scoped>
.coupon-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 80px;
  
  .coupon-card {
    margin: 15px;
    background: linear-gradient(to right, #ff9500, #ff6000);
    border-radius: 12px;
    color: #fff;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(255, 149, 0, 0.3);
    position: relative;
    
    &.used,
    &.expired {
      background: linear-gradient(to right, #bbb, #999);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    .coupon-header {
      padding: 20px;
      text-align: center;
      border-bottom: 1px dashed rgba(255, 255, 255, 0.3);
      
      .coupon-amount {
        display: flex;
        align-items: baseline;
        justify-content: center;
        
        .symbol {
          font-size: 20px;
          margin-right: 4px;
        }
        
        .value {
          font-size: 48px;
          font-weight: bold;
        }
      }
      
      .coupon-condition {
        font-size: 14px;
        margin-top: 8px;
        opacity: 0.9;
      }
    }
    
    .coupon-info {
      padding: 15px 20px;
      
      .info-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .info-label {
          font-size: 14px;
          opacity: 0.8;
        }
        
        .info-value {
          font-size: 14px;
          font-weight: 500;
          
          &.code {
            background-color: rgba(255, 255, 255, 0.2);
            padding: 2px 8px;
            border-radius: 4px;
            letter-spacing: 1px;
          }
        }
      }
    }
    
    .coupon-status {
      position: absolute;
      right: 20px;
      top: 20px;
      
      .status-stamp {
        width: 60px;
        height: 60px;
        opacity: 0.8;
      }
    }
  }
  
  .detail-section {
    margin: 15px;
    background-color: #fff;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    
    .section-title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 10px;
      position: relative;
      padding-left: 10px;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 3px;
        height: 16px;
        background-color: #ff6000;
        border-radius: 3px;
      }
    }
    
    .section-content {
      color: #666;
      font-size: 14px;
      
      .instruction-item,
      .rule-item {
        margin-bottom: 8px;
        line-height: 1.5;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
  
  .detail-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 10px 15px;
    background-color: #fff;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    z-index: 10;
    
    .footer-buttons {
      display: flex;
      justify-content: space-between;
      gap: 10px;
      
      .nut-button {
        flex: 1;
      }
    }
  }
}
</style>